use serde::{Deserialize, Serialize};
use std::env;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    pub database_url: String,
    pub server_host: String,
    pub server_port: u16,
    pub oidc_issuer: String,
    pub oidc_client_id: String,
    pub oidc_jwks_url: String,
    pub jwt_secret: String,
    pub cache_max_capacity: u64,
    pub cache_ttl_seconds: u64,
}

impl Config {
    pub fn from_env() -> anyhow::Result<Self> {
        Ok(Self {
            database_url: env::var("DATABASE_URL")
                .unwrap_or_else(|_| "postgres://user:password@localhost/db".to_string()),
            server_host: env::var("SERVER_HOST").unwrap_or_else(|_| "127.0.0.1".to_string()),
            server_port: env::var("SERVER_PORT")
                .unwrap_or_else(|_| "8080".to_string())
                .parse()?,
            oidc_issuer: env::var("OIDC_ISSUER")
                .unwrap_or_else(|_| "https://your-oidc-provider".to_string()),
            oidc_client_id: env::var("OIDC_CLIENT_ID")
                .unwrap_or_else(|_| "your-client-id".to_string()),
            oidc_jwks_url: env::var("OIDC_JWKS_URL")
                .unwrap_or_else(|_| "https://your-oidc-provider/.well-known/jwks.json".to_string()),
            jwt_secret: env::var("JWT_SECRET")
                .unwrap_or_else(|_| "your-secret-key".to_string()),
            cache_max_capacity: env::var("CACHE_MAX_CAPACITY")
                .unwrap_or_else(|_| "10000".to_string())
                .parse()
                .unwrap_or(10000),
            cache_ttl_seconds: env::var("CACHE_TTL_SECONDS")
                .unwrap_or_else(|_| "3600".to_string())
                .parse()
                .unwrap_or(3600),
        })
    }

    pub fn server_address(&self) -> String {
        format!("{}:{}", self.server_host, self.server_port)
    }
}